﻿


var tempID;//保存当前的选项的Id;
var gdViewModel;

var IsError; //1表示出错binddata
var IsClick = '';//1表示提交过数据
$(function () {
    //向导初始化
    $("#ShowDownLoadID").hide();
    $('#bootstrap-wizard-1').bootstrapWizard({
        'tabClass': 'form-wizard',
        onTabClick: function (tab, navigation, index) {
            return false;
        },
        //点击“上一步”
        'onPrevious': function (tab, navigation, index) {
            var $total = navigation.find('li').length;
            var $current = index + 1;//预获取下一个Index
            if ($current >= $total) {
                $('#bootstrap-wizard-1').find('.pager .next').hide();
                $('#bootstrap-wizard-1').find('.pager .finish').show();
                $('#bootstrap-wizard-1').find('.pager .finish').removeClass('disabled');
            } else {
                $('#bootstrap-wizard-1').find('.pager .next').show();
                $('#bootstrap-wizard-1').find('.pager .finish').hide();
            }
        },
        //点击“下一步”
        'onNext': function (tab, navigation, index) {


            var $total = navigation.find('li').length;
            var $current = index + 1;//预获取下一个Index
            if ($current < $total) {
                $('#bootstrap-wizard-1').find('.pager .next').show();
                $('#bootstrap-wizard-1').find('.pager .finish').hide();

            }

            if (index == 1)
            {
                confirm("你确定使用当前的数据库表吗？")  //确认信息test

                gdViewModel.GetTargetTable();//获取当前选中的目标表
               
             
            }
            else if (index == 2)
            {
                var boolflag = gdViewModel.FileTypeValidate();//获取验证文件类型
                
                if (boolflag) { //文件类型合法
                    gdViewModel.ReBackData();
                    if (IsError==0) {
                        return false;
                    }
                }
                else {
                    return false;
                } 
            }
            else if (index == 3)
            {
               
                $("#hrefID").removeClass("disabled");
                gdViewModel.IsAddUnExistData();//获取复选框是否要添加数据
                gdViewModel.IsClearMainTable();//获取复选框勾选是否需要清除主表的信息
               
                gdViewModel.MarkIsAddAndClear();
              
            }
            else if (index == 4) {
                
                if (IsClick != 1) {
                    alert("必须先点击" + "提交数据" + "才能继续执行下一步");
                    return false;

                }  
           }

            $('#bootstrap-wizard-1').find('.form-wizard').children('li').eq(index - 1).addClass(
              'complete');
            $('#bootstrap-wizard-1').find('.form-wizard').children('li').eq(index - 1).find('.step')
            .html('<i class="fa fa-check"></i>');
        }
    });



    function gridViewModel() {
        var self = this;


        self.recordSet = ko.observableArray(); //选项数据集
        self.HerfStr = ko.observable();//获取链接
        self.SetData = ko.observableArray();//test;获取源字段HerfStr 
        //初始化
        self.init = function () {
            $("#hrefID").addClass("disabled");  //设置“提交数据按钮为不可用”
            self.SearchTable();
        }
        self.initEd = function () {//结束初始化
        }

        //通用试题导入第一步，选取数据库表集
        self.SearchTable = function () {

            $.ajax(
            {

                url: '/api/CommonDataImport/init/',
                type: "get",
                success: function (result) {
                    if (result == null) {
                        result = "当前数据库不存在数据库表！";
                    }
                   
                        self.recordSet(result);//收集返回的数据库表集
                    
                }
            });
        };


        //TO Add Method  

        //验证选择的文件时候合法
        self.FileTypeValidate = function ()
        {
            if ($("#fileID").val() == null) { //如果没有上传文件
            
                alert("请上传指定格式的Excel文件~~");
                return false;
            }
            else {
                var str = $("#fileID").val();//获取选择的文件名字符串
                var index = str.lastIndexOf('.');
                var strtype = str.substr(index, str.length);//获取文件的后缀
                strtype = strtype.toLowerCase();  //转换成小写
                if (strtype != ".xls") {  //如果不是有效的文件格式
                    alert("请上传xls格式的Excel文件！");
                    return false;
                }
                else {

                    return true;
                }
            }
        }
        //是否删除原主表的数据  10.10
        self.IsClearMainTable = function ()
        {
            var IsChecked = $('input:checkbox[name="IsClearMainTable"]:checked').val();   //清空原有主表复选框被勾选
            if (IsChecked == null)
            {
                IsChecked = 0;//如果未被勾选，则赋值为0
            }
            $.ajax({
                url: '/api/CommonDataImport/ValidateIsClearMainTable?IsChecked=' + IsChecked,
                type: 'POST',
                success: function () {  //成功方法未写
                }
            })
        }


        //点击“提交数据”按钮，导入数据
        self.SubmitData = function ()
        {
            self.InsertData();
            IsClick = 1;
            $("#hrefID").addClass("disabled");
        }

        //是否向附表追加不存在字段 10.10
        self.IsAddUnExistData = function () {
            var IsChecked = $('input:checkbox[name="IsAddUnExistData"]:checked').val();   //是否向附表追加不存在字段复选框被勾选
            if (IsChecked == null) {
                IsChecked = 0;//如果未被勾选，则赋值为0
            }
            $.ajax({
                url: '/api/CommonDataImport/ValidateIsAddUnExistData?IsChecked=' + IsChecked,
                type: 'POST',
                success: function () {  //成功方法未写
                }
            })

        }

        //获取选中的目标表10.10
        self.GetTargetTable = function () {
             var  getSelectedTableName = $("#select-1").val();
            
            $.ajax({
                url: '/api/CommonDataImport/GetCurrentChosenTargetTable?TargetTable=' + getSelectedTableName,
                type: 'POST',
                success: function () {  //成功方法未写

                }
            })

        }
        //将文件里面的源表属性和对应的目标字段绑上去10.10
        self.ReBackData = function () {
            $.ajax({
                url: '/api/CommonDataImport/BindData/',
                type: 'POST',
                
                success: function (result) {  //返回ImportStruct
                   
                    if (result.StrError == null || result.StrError =='') {
                        self.SetData(result.structList);
                        IsError = 1;  //成功绑定数据
                   
                    }
                    else {
                        IsError = 0;  //绑定数据不成功
                        alert(result.StrError); 
                    }
                }
            })
         

        }
        //标记选中的是否清除原表，是否向副表插入不存在数据
        self.MarkIsAddAndClear = function ()
        {
            var IsClear = $('input:checkbox[name="IsClearMainTable"]:checked').val();   //清空原有主表复选框被勾选
            if (IsClear == 1) {
                $("#IsClearMainTableMarked").show();
                $("input:checkbox[name='IsClearMainTableMarked'][ value='" + IsClear + "']").attr("checked", true);//标记选中
                $("input:checkbox[name='IsClearMainTableMarked'][ value='" + IsClear + "']").attr("disabled", 'disabled');//标记为不可选
            }
            else {
                $("#IsClearMainTableMarked").hide();
            }
            var IsAdd = $('input:checkbox[name="IsAddUnExistData"]:checked').val();   //是否向附表追加不存在字段复选框被勾选
            if (IsAdd == 1)
            {
                $("#IsAddUnExistDataMarked").show();
                $("input:checkbox[name='IsAddUnExistDataMarked'][ value='" + IsAdd + "']").attr("checked", true);
                $("input:checkbox[name='IsAddUnExistDataMarked'][ value='" + IsAdd + "']").attr("disabled", 'disabled');
            }
            else {
                $("#IsAddUnExistDataMarked").hide();
            }
        }

        //向数据库导入数据10.10
        self.InsertData = function ()
        {


            $.ajax({
                url: '/api/CommonDataImport/btnImportDataClick/',
                type: 'POST',
                success: function (result)
                {
                    if (result.StrErrorOrNot != null)
                    {
                        alert(result.StrErrorOrNot);
                    }
                    if (result.DownLoadUrl != null &&result.DownLoadUrl != "") {
                        
                        $("#ShowDownLoadID").show();
                        var StrHerf = "<a href='" + result.DownLoadUrl + "' class='btn btn-success btn-labeled 'role='button' ><span class='btn-label'><i class='fa fa-download'></i></span>错误导入信息</a>";
                        $("#ShowDownLoadID").append(StrHerf);
                       
                    }
                    else {
                        $("#ShowDownLoadID").hide();
                    }
                   

                }
            })

        }



        


    }
    //点击“上传文件”，把选择的文件保存到指定的文件夹中
    $("#bootstrapped-fine-uploader").fineUploader({
        request: {

            endpoint: '/Api/CommonDataImport/btnExcelUploadClick',
        },

        text: {

            uploadButton: '<span class="btn-label"><i class="glyphicon glyphicon-open"></i></span> 上传文件'

        },
        validation:

                {

                    allowedExtensions: ['xls'],

                    sizeLimit: 524288000 // 500MB = 10 * 1024kb * 1024 bytes

                },
        template:

               '<div class="qq-uploader span12">' +
             '<pre class="qq-upload-drop-area span12"><span>{dragZoneText}</span></pre>' +
           '<div id="qq-upload-button" class="qq-upload-button btn btn-success btn-labeled" style="width: 100%; margin:5px;height:30px;">{uploadButtonText}</div>' +
              '<span class="qq-drop-processing">' +
                 '<span class="qq-drop-processing-spinner"></span></span>' +
             '<ul class="qq-upload-list" style="margin-top: 10px; text-align: center;display:none;"></ul>' +
                '</div>',
        classes: {

            success: 'alert alert-success',

            fail: 'alert alert-error'

        },
        debug: true
    }).on('complete', function (event, id, fileName, responseJSON) {
        $("#fileID").val(responseJSON);
    })

    var gdViewModel = new gridViewModel();
    gdViewModel.init();
    ko.applyBindings(gdViewModel);





});
